import React, { useContext, useEffect, useState } from 'react';
import dayjs from 'dayjs';
import {
  Form,
  Input,
  DatePicker,
  Button,
  Grid,
  Select,
} from '@arco-design/web-react';
import { GlobalContext } from '@/context';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import { IconRefresh } from '@arco-design/web-react/icon';
import cs from 'classnames';
import styles from './style/index.module.less';
import { EnumsRes } from '@/api/interface';
import { Enums } from '@/api/modules';
import { entityGet } from '@/api/modules/entity';
import { AssignedPerson } from '@/api/modules/violation';
import { AssignedPersonItem } from '@/api/interface/violation';
import useIsMountedRef from '@/utils//useIsMountedRef';
import debounce from 'lodash/debounce';

import { DataWrapper } from '@/utils/dataWrapper';
import Status from '@/components/Status';

const { Row, Col } = Grid;
const Option = Select.Option;
const { useForm } = Form;

function SearchForm(props: {
  onSearch: (values: Record<string, unknown>) => void;
  value: any;
}) {
  const { lang, rtl } = useContext(GlobalContext);
  const t = useLocale(locale);
  const [form] = useForm();

  const [entitys, setEntitys] = useState([]);
  const getEntitys = async () => {
    try {
      const { data } = await entityGet({ active: true });
      if (isMountedRef.current) {
        setEntitys(data);
      }
    } catch (e) {}
  };

  const [enums, setEnums] = useState<{ [key: string]: EnumsRes[] }>({
    sourceEnums: [],
    violationStatusEnums: [],
    violationTypeEnums: [],
    violationInternalTypeEnums: [],
    actionTakenEnums: [],
  });
  const getEnums = async () => {
    try {
      const enumData = await Promise.all([
        Enums({ type: 'SourceEnums' }),
        Enums({ type: 'ViolationStatusEnums' }),
        Enums({ type: 'ViolationTypeEnums' }),
        Enums({ type: 'ViolationInternalTypeEnums' }),
        Enums({ type: 'ActionTakenEnums' }),
      ]);
      if (isMountedRef.current) {
        setEnums({
          sourceEnums: enumData[0].data,
          violationStatusEnums: DataWrapper(enumData[1].data),
          violationTypeEnums: enumData[2].data,
          violationInternalTypeEnums: enumData[3].data,
          actionTakenEnums: enumData[4].data,
        });
      }
    } catch (e) {}
  };

  const [assignedPerson, setAssignedPerson] = useState<
    Array<AssignedPersonItem>
  >([]);
  const getAssignedPerson = async () => {
    try {
      const { data } = await AssignedPerson({});
      if (isMountedRef.current) {
        setAssignedPerson(data);
      }
    } catch (e) {}
  };
  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    getEntitys();
    getAssignedPerson();
    getEnums();
  }, []);

  const handleSubmit = debounce(() => {
    const values = form.getFieldsValue();
    if (values.q) {
      values.q = values.q.trim();
    }
    props.onSearch(values);
  }, 0);

  const handleReset = debounce(() => {
    form.resetFields();
    props.onSearch({});
  }, 0);

  const colSpan = 12;

  return (
    <div className={cs(styles['search-form-wrapper'], rtl ? 'rtl' : '')}>
      <Form
        form={form}
        className={rtl ? styles['search-formrtl'] : styles['search-form']}
        labelAlign="right"
        labelCol={{ span: lang === 'ar-EG' ? 8 : 7 }}
        wrapperCol={{ span: lang === 'ar-EG' ? 16 : 17 }}
        onValuesChange={handleSubmit}
        initialValues={props.value}
      >
        <Row gutter={24}>
          <Col span={colSpan}>
            <Form.Item label={t['searchTable.form.q']} field="q">
              <Input
                allowClear
                autoComplete="off"
                placeholder={t['searchTable.form.q.placeholder']}
              />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              label={t['searchTable.columns.boxType']}
              field="violationBoxType"
            >
              <Select
                allowClear
                placeholder={t['searchTable.select.placeholder']}
                triggerProps={{
                  autoAlignPopupWidth: false,
                  autoAlignPopupMinWidth: true,
                }}
              >
                {enums.violationInternalTypeEnums.map((option, index) => (
                  <Option key={index} value={option.key}>
                    {option.value[lang === 'en-US' ? 'en' : 'ar']}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              label={t['searchTable.columns.person']}
              field="assignedPerson"
            >
              <Select
                allowClear
                showSearch
                placeholder={t['searchTable.select.placeholder']}
                triggerProps={{
                  autoAlignPopupWidth: false,
                  autoAlignPopupMinWidth: true,
                }}
                filterOption={(inputValue, option) => {
                  return (
                    option.props.children
                      .toLowerCase()
                      .indexOf(inputValue.toLowerCase()) >= 0
                  );
                }}
              >
                {assignedPerson.map((option, index) => (
                  <Option key={index} value={option.id}>
                    {`${option.name}(${option.count})`}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              label={t['searchTable.columns.entityName']}
              field="entityId"
            >
              <Select
                allowClear
                showSearch
                triggerProps={{
                  autoAlignPopupWidth: false,
                  autoAlignPopupMinWidth: true,
                }}
                placeholder={t['searchTable.select.placeholder']}
                filterOption={(inputValue, option) => {
                  return (
                    option.props.children
                      .toLowerCase()
                      .indexOf(inputValue.toLowerCase()) >= 0
                  );
                }}
              >
                {entitys.map((option, index) => (
                  <Option key={index} value={option?.id}>
                    {option[lang === 'en-US' ? 'name' : 'nameAr']}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              label={t['searchTable.columns.type']}
              field="violationType"
            >
              <Select
                allowClear
                placeholder={t['searchTable.select.placeholder']}
                triggerProps={{
                  autoAlignPopupWidth: false,
                  autoAlignPopupMinWidth: true,
                }}
              >
                {enums.violationTypeEnums.map((option, index) => (
                  <Option key={index} value={option.key}>
                    {option.value[lang === 'en-US' ? 'en' : 'ar']}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item label={t['searchTable.columns.status']} field="status">
              <Select
                allowClear
                placeholder={t['searchTable.select.placeholder']}
                triggerProps={{
                  autoAlignPopupWidth: false,
                  autoAlignPopupMinWidth: true,
                }}
              >
                {enums.violationStatusEnums.map((option, index) => (
                  <Option key={index} value={option.key}>
                    <div className={rtl ? 'rtl' : ''}>
                      <Status status={option?.key}></Status>
                      {option.value[lang === 'en-US' ? 'en' : 'ar']}
                    </div>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              label={t['searchTable.columns.taken']}
              field="actionTaken"
            >
              <Select
                allowClear
                placeholder={t['searchTable.select.placeholder']}
                triggerProps={{
                  autoAlignPopupWidth: false,
                  autoAlignPopupMinWidth: true,
                }}
              >
                {enums.actionTakenEnums.map((option, index) => (
                  <Option key={index} value={option.key}>
                    {option.value[lang === 'en-US' ? 'en' : 'ar']}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item label={t['searchTable.columns.source']} field="source">
              <Select
                allowClear
                placeholder={t['searchTable.select.placeholder']}
                triggerProps={{
                  autoAlignPopupWidth: false,
                  autoAlignPopupMinWidth: true,
                }}
              >
                {enums.sourceEnums.map((option, index) => (
                  <Option key={index} value={option.key}>
                    {option.value[lang === 'en-US' ? 'en' : 'ar']}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col span={colSpan}>
            <Form.Item label={t['searchTable.columns.created']} field="Date">
              <DatePicker.RangePicker
                allowClear
                style={{ width: '100%' }}
                format="YYYY-MM-DD"
                disabledDate={(date) => dayjs(date).isAfter(dayjs())}
              />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div className={rtl ? styles['right-buttonrtl'] : styles['right-button']}>
        {/* <Button type="primary" icon={<IconSearch />} onClick={handleSubmit}>
          {t['searchTable.form.search']}
        </Button> */}
        <Button
          icon={<IconRefresh />}
          onClick={handleReset}
          className={styles['button']}
        >
          {t['searchTable.form.reset']}
        </Button>
      </div>
    </div>
  );
}

export default SearchForm;
